//
//  UserAccount.swift
//  SwiftWeiBo
//
//  Created by wyw on 16/10/9.
//  Copyright © 2016年 Style_Y. All rights reserved.
//

import UIKit

class UserAccount: NSObject ,NSCoding{
    /// 用于调用access_token，接口获取授权后的access token。
    var access_token: String?
    /// access_token的生命周期，单位是秒数。
    var expires_in: NSNumber? {
        didSet{
           expires_Date = Date(timeIntervalSinceNow: expires_in!.doubleValue)
            print(expires_Date)
        }
    }
    
    /// 过期时间
    var expires_Date:Date?
    
    /// 当前授权用户的UID。
    var uid:String?
    
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    /// 用户昵称
    var screen_name: String?
    
    init(dict:[String : AnyObject]){
//        access_token = dict["access_token"] as? String
//        expires_in = dict["expires_in"] as? NSNumber
//        uid = dict["uid"] as? String
        super.init()
        setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
//        print(key)
    }
    
    override var description: String {
        // 1.定义属性数组
        let properties = ["access_token", "expires_in", "uid", "expires_Date", "avatar_large", "screen_name"]
        
        // 2.根据属性数组，将属性转换为字典
        let dict = self.dictionaryWithValues(forKeys: properties)
        
        // 3.将字典转换为字符串
        return "\(dict)"
        
    }
    
    /// 下载用户信息
    func loadUserInfo(_ finished: @escaping (_ accout:UserAccount? , _ error:Error?)->()) {
        assert(access_token != nil, "没有授权")

        let path = "2/users/show.json"
        let params = ["access_token":access_token!, "uid":uid!]
        
        NetWorkTools.shareNetWorkTools().get(path, parameters: params, progress: { (_) in
            
            }, success: { (_, JSON) in
                // 判断字典是否有值
                if let dict = JSON as? [String:AnyObject]
                {
                    self.screen_name = dict["screen_name"] as? String
                    self.avatar_large = dict["avatar_large"] as? String
                    
                    finished(self, nil)
                }
                
            }) { (_, error) in
                    finished(nil, error)
        }
        
    }
    
    // MARK: - 是否登录过
    class func userLogin() -> Bool {
      return UserAccount.loadAccount() != nil
    }
    
    // MARK: - NSCoding  数据存储与读取
    
    static let filePath = "account.plist".cacheDir()
    
    // 存储
    func saveAccount()
    {
        let b = NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.filePath)
        if b {
          print("保存成功")
        } else {
          print("保存失败")
        }
    }
    
    // 读取
    static var account: UserAccount?
    class func loadAccount() -> UserAccount?
    {
        // 1.判断是否已经有值
        if account != nil {
            return account
        }
        // 2.加载授权模型
        account = NSKeyedUnarchiver.unarchiveObject(withFile: UserAccount.filePath) as? UserAccount
        
        // 3.判断是否过期
        if  account?.expires_Date?.compare(Date()) == ComparisonResult.orderedAscending {
            // 过期
           return nil
        }
        
        return account
    }
    
    // 编码
    func encode(with aCoder: NSCoder)
    {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expires_in, forKey: "expires_in")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(expires_Date, forKey: "expires_Date")
        aCoder.encode(screen_name, forKey: "screen_name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
    }
    
    // 解码
    required init?(coder aDecoder: NSCoder)
    {
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        expires_in = aDecoder.decodeObject(forKey: "expires_in") as? NSNumber
        uid = aDecoder.decodeObject(forKey: "uid") as? String
        expires_Date = aDecoder.decodeObject(forKey: "expires_Date") as? Date
        screen_name = aDecoder.decodeObject(forKey: "screen_name")  as? String
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large")  as? String
    }
}



































